package com.zyj.websocket2;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;


public class EndpointHandler extends TextWebSocketHandler {

    private static final Map<WebSocketSession, WebSocketSession> ALL_SESSIONS = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//        session.setTextMessageSizeLimit(1024 * 1024 * 9916);
        System.out.println(this);
        System.out.println(session.getUri());
        super.afterConnectionEstablished(session);
        System.out.println("afterConnectionEstablished");
        session.sendMessage(new TextMessage("established"));
        ALL_SESSIONS.put(
                session,
//                new ConcurrentWebSocketSessionDecorator(session, 10 * 1000, 1024 * 1024 * 4)
                new MyConcurrentWebSocketSessionDecorator(session)
        );
//        ALL_SESSIONS.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        System.out.println("afterConnectionClosed");
        System.out.println(session);
        System.out.println(status);
        ALL_SESSIONS.remove(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        System.out.println(session);
        System.out.println(message);
        System.out.println(message.getPayload());
        session.sendMessage(new TextMessage(message.getPayload()));
    }

    public void broadcast(String msg) {
        for (WebSocketSession session : ALL_SESSIONS.values()) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
                session.sendMessage(new TextMessage(msg));
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
